<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - 组态可视化系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-container {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
            width: 100%;
            max-width: 400px;
            text-align: center;
        }

        .logo {
            font-size: 48px;
            margin-bottom: 20px;
        }

        h1 {
            color: white;
            margin-bottom: 10px;
            font-size: 28px;
            font-weight: 300;
        }

        .subtitle {
            color: rgba(255, 255, 255, 0.7);
            margin-bottom: 40px;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        label {
            display: block;
            color: white;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 500;
        }

        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 15px 20px;
            border: none;
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.1);
            color: white;
            font-size: 16px;
            transition: all 0.3s;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        input[type="text"]:focus,
        input[type="password"]:focus {
            outline: none;
            background: rgba(255, 255, 255, 0.15);
            border-color: rgba(255, 152, 0, 0.5);
            box-shadow: 0 0 0 3px rgba(255, 152, 0, 0.2);
        }

        input::placeholder {
            color: rgba(255, 255, 255, 0.5);
        }

        .login-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(45deg, #FF9800, #F57C00);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 10px;
        }

        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(255, 152, 0, 0.4);
        }

        .login-btn:active {
            transform: translateY(0);
        }

        .login-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .error-message {
            color: #ff6b6b;
            font-size: 14px;
            margin-top: 15px;
            padding: 10px;
            background: rgba(255, 107, 107, 0.1);
            border-radius: 8px;
            border: 1px solid rgba(255, 107, 107, 0.3);
            display: none;
        }

        .loading {
            display: none;
            color: white;
            margin-top: 15px;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .demo-info {
            margin-top: 30px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .demo-info h3 {
            color: white;
            font-size: 16px;
            margin-bottom: 10px;
        }

        .demo-info p {
            color: rgba(255, 255, 255, 0.7);
            font-size: 13px;
            line-height: 1.5;
        }

        .demo-credentials {
            background: rgba(255, 152, 0, 0.1);
            border: 1px solid rgba(255, 152, 0, 0.3);
            border-radius: 8px;
            padding: 10px;
            margin-top: 10px;
        }

        .demo-credentials strong {
            color: #FF9800;
        }

        /* 管理员入口按钮 */
        .admin-link {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .admin-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            position: relative;
            overflow: hidden;
        }

        .admin-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }

        .admin-btn:hover::before {
            left: 100%;
        }

        .admin-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }

        .admin-btn:active {
            transform: translateY(0);
        }

        /* 响应式设计 */
        @media (max-width: 480px) {
            .login-container {
                margin: 20px;
                padding: 30px 20px;
            }
            
            h1 {
                font-size: 24px;
            }
            
            .logo {
                font-size: 40px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">🎮</div>
        <h1>Three.js 项目</h1>
        <p class="subtitle">请输入您的账号和密码</p>
        
        <form id="loginForm">
            <div class="form-group">
                <label for="username">账号</label>
                <input 
                    type="text" 
                    id="username" 
                    name="username" 
                    placeholder="请输入账号"
                    autocomplete="username"
                    required
                >
            </div>
            
            <div class="form-group">
                <label for="password">密码</label>
                <input 
                    type="password" 
                    id="password" 
                    name="password" 
                    placeholder="请输入密码"
                    autocomplete="current-password"
                    required
                >
            </div>
            
            <button type="submit" class="login-btn" id="loginBtn">
                登录
            </button>
            
            <div class="error-message" id="errorMessage">
                账号或密码错误，请重试
            </div>
            
            <div class="loading" id="loading">
                <div class="spinner"></div>
                正在登录...
            </div>
        </form>
        
        <div class="demo-info">
            <h3>📋 演示账号</h3>
            <p>这是一个演示项目，您可以使用以下默认账号登录：</p>
            <div class="demo-credentials">
                <strong>账号：</strong>123<br>
                <strong>密码：</strong>123
            </div>
            
            <!-- 管理员入口 -->
            <div class="admin-link">
                <button class="admin-btn" id="adminBtn">
                    ⚙️ 管理员设置
                </button>
            </div>
        </div>
    </div>

    <script type="module">
        // 导入配置管理器
        import configManager from './scripts/core/config.js';
        
        // 等待配置加载
        await configManager.loadConfig();
        
        // 应用配置
        configManager.applyConfig();
        
        // 获取认证配置
        let authConfig = configManager.getAuthConfig();
        
        // 🔐 立即检查认证状态，如果禁用则跳过登录
        if (authConfig.enabled === false) {
            const returnUrl = sessionStorage.getItem('returnUrl') || 'index.html';
            sessionStorage.removeItem('returnUrl');
            window.location.href = returnUrl;
            // 停止后续代码执行
            throw new Error('Redirecting to main app (auth disabled)');
        }
        
        // 设置页面标题
        document.title = '登录 - 组态可视化系统';
        
        // 从后端获取默认用户账号信息并显示
        async function loadDefaultUserInfo() {
            try {
                const response = await fetch('/api/accounts/users');
                if (response.ok) {
                    const result = await response.json();
                    if (result.success && result.data.length > 0) {
                        // 查找默认用户账号
                        const defaultUser = result.data.find(user => user.isDefault);
                        if (defaultUser) {
                            const demoCredentials = document.querySelector('.demo-credentials');
                            if (demoCredentials) {
                                demoCredentials.innerHTML = `
                                    <strong>账号：</strong>${defaultUser.username}<br>
                                    <strong>密码：</strong>请联系管理员获取
                                `;
                            }
                        }
                    }
                }
            } catch (error) {
                console.warn('⚠️ 加载默认用户信息失败:', error.message);
                // 失败时使用配置中的值作为备用
                if (authConfig.defaultUsername) {
                    const demoCredentials = document.querySelector('.demo-credentials');
                    if (demoCredentials) {
                        demoCredentials.innerHTML = `
                            <strong>账号：</strong>${authConfig.defaultUsername}<br>
                            <strong>密码：</strong>${authConfig.defaultPassword || '***'}
                        `;
                    }
                }
            }
        }
        
        // 加载默认用户信息
        loadDefaultUserInfo();
        
        // 管理员按钮点击事件
        document.getElementById('adminBtn').addEventListener('click', function() {
            window.location.href = 'admin.html';
        });
        
        // 登录表单处理
        document.getElementById('loginForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();
            const loginBtn = document.getElementById('loginBtn');
            const errorMessage = document.getElementById('errorMessage');
            const loading = document.getElementById('loading');
            
            // 隐藏错误信息
            errorMessage.style.display = 'none';
            
            // 显示加载状态
            loginBtn.disabled = true;
            loading.classList.add('show');
            
            try {
                // 调用后端 API 进行认证
                const response = await fetch('/api/auth/user-login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // 登录成功
                    // 保存登录状态
                    localStorage.setItem('isLoggedIn', 'true');
                    localStorage.setItem('username', username);
                    localStorage.setItem('loginTime', new Date().toISOString());
                    localStorage.setItem('sessionTimeout', authConfig.sessionTimeout || 24);
                    
                    // 跳转到主应用
                    const returnUrl = sessionStorage.getItem('returnUrl') || 'index.html';
                    sessionStorage.removeItem('returnUrl'); // 清除返回URL
                    
                    window.location.href = returnUrl;
                } else {
                    // 登录失败
                    // 显示错误信息
                    errorMessage.textContent = result.error || '账号或密码错误，请重试';
                    errorMessage.style.display = 'block';
                    
                    // 恢复按钮状态
                    loginBtn.disabled = false;
                    loading.classList.remove('show');
                    
                    // 清空密码框
                    document.getElementById('password').value = '';
                    document.getElementById('password').focus();
                }
            } catch (error) {
                console.error('❌ 登录请求失败:', error);
                
                // 网络错误
                errorMessage.textContent = '网络连接失败，请检查后端服务器是否运行';
                errorMessage.style.display = 'block';
                
                // 恢复按钮状态
                loginBtn.disabled = false;
                loading.classList.remove('show');
                
                // 清空密码框
                document.getElementById('password').value = '';
                document.getElementById('password').focus();
            }
        });
        
        // 从服务器获取认证配置
        async function fetchAuthConfig() {
            try {
                // 优先从后端API获取
                const response = await fetch('/api/config');
                if (response.ok) {
                    const result = await response.json();
                    if (result.success && result.data.auth) {
                        return result.data.auth;
                    }
                }
                throw new Error('服务器配置获取失败');
            } catch (error) {
                console.warn('⚠️ 从服务器获取配置失败，使用本地配置:', error.message);
                // 降级：使用本地 configManager
                return configManager.getAuthConfig();
            }
        }
        
        // 检查是否已有有效登录状态
        const isLoggedIn = localStorage.getItem('isLoggedIn');
        const loginTime = localStorage.getItem('loginTime');
        const sessionTimeout = localStorage.getItem('sessionTimeout') || authConfig.sessionTimeout || 24;
        
        // 如果已登录且登录时间在有效期内，直接跳转
        if (isLoggedIn === 'true' && loginTime) {
            const loginDate = new Date(loginTime);
            const now = new Date();
            const hoursDiff = (now - loginDate) / (1000 * 60 * 60);
            
            if (hoursDiff < sessionTimeout) {
                const returnUrl = sessionStorage.getItem('returnUrl') || 'index.html';
                sessionStorage.removeItem('returnUrl');
                window.location.href = returnUrl;
                // 停止后续代码执行
                throw new Error('Redirecting to main app (already logged in)');
            } else {
                // 登录过期，清除状态
                localStorage.removeItem('isLoggedIn');
                localStorage.removeItem('username');
                localStorage.removeItem('loginTime');
                localStorage.removeItem('sessionTimeout');
            }
        }
        
        // 页面完全加载后，聚焦到用户名输入框
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                document.getElementById('username')?.focus();
            });
        } else {
            document.getElementById('username')?.focus();
        }
        
        // 回车键快速登录
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                const form = document.getElementById('loginForm');
                if (form.checkValidity()) {
                    form.dispatchEvent(new Event('submit'));
                }
            }
        });
        
        // 输入框动画效果
        const inputs = document.querySelectorAll('input[type="text"], input[type="password"]');
        inputs.forEach(input => {
            input.addEventListener('focus', function() {
                this.parentElement.style.transform = 'translateY(-2px)';
            });
            
            input.addEventListener('blur', function() {
                this.parentElement.style.transform = 'translateY(0)';
            });
        });
    </script>
</body>
</html>
